<template>
    <div class='m-b-10'>
        <a-button type='primary' @click='addNew(null)'>{{$t('add')}}</a-button>
    </div>
    <div>
        <BTable name-key='name' :columns='columns' :data='dataRows' row-key='id'>
            <template #type='{record}'>
                <a-tag v-if='record.type == "FOLD"' color='#108ee9'>{{$t('fold')}}</a-tag>
                <a-tag v-else-if='record.type == "PAGE"' color='#2db7f5'>{{$t('page')}}</a-tag>
                <a-tag v-else-if='record.type == "BUTTON"' color='#87d068'>{{$t('button')}}</a-tag>
            </template>
            <template #enable='{record}'>
                <a-tag v-if='record.enable' color='#87d068'>{{$t('enable')}}</a-tag>
                <a-tag v-else>{{$t('disable')}}</a-tag>
            </template>
            <template #display='{record}'>
                <template v-if='record.type === "FOLD" || record.type === "PAGE"'>
                    <a-tag v-if='record.display == 1' color='#87d068'>{{$t('yes')}}</a-tag>
                    <a-tag v-else>{{$t('no')}}</a-tag>
                </template>
                <span v-else></span>
            </template>
            <template #keeAlive='{record}'>
                <template v-if='record.type === "PAGE"'>
                    <a-tag v-if='record.keeAlive == 1' color='#87d068'>{{$t('yes')}}</a-tag>
                    <a-tag v-else>{{$t('no')}}</a-tag>
                </template>
                <span v-else></span>
            </template>
            <template #$action='{record}'>
                <BTextButton @click='addNew(record)'>{{$t('add')}}</BTextButton>
            </template>
        </BTable>   
    </div>
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close='close'>
        <a-form ref='formRef' :label-col='{span : 5}' :rules='rules' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item :label='$t("superMenu")' name='parentId'>
                <a-tree-select show-search :disabled='formData.id' v-model:value='formData.parentId' :tree-data='parentOptions' :field-names='{children : "children", label : "label", value : "id"}'></a-tree-select>
                <!-- <a-select disabled v-model:value='formData.parentId' :options='parentOptions'></a-select> -->
            </a-form-item>
            <a-form-item :label='$t("type")' name='type'>
                <a-select :disabled='formData.id' v-model:value='formData.type' :options='typesOptions'></a-select>
            </a-form-item>
            <a-form-item :label='$t("name")' name='name'>
                <a-input type='text' v-model:value='formData.name' showCount :maxlength="30" />
            </a-form-item>
            <template v-if='formData.type === "FOLD" || formData.type === "PAGE"'>
                <a-form-item :label='$t("path")' name='path'>
                    <a-input type='text' v-model:value='formData.path' showCount :maxlength="50" />
                </a-form-item>
                <a-form-item :label='$t("component")' name='component'>
                    <a-input type='text' v-model:value='formData.component' showCount :maxlength="50" />
                </a-form-item>
            </template>
            <a-form-item :label='$t("permissionSymbol")' name='permission'>
                <a-input type='text' v-model:value='formData.permission' showCount :maxlength="100" />
            </a-form-item>
            <a-form-item label='API' name='api'>
                <a-input type='text' v-model:value='formData.api' showCount :maxlength="100" />
            </a-form-item>
            <a-form-item :label='"API" + $t("method")' name='apiMethod'>
                <a-select allowClear v-model:value='formData.apiMethod' :options='apiMethodOptions'></a-select>
            </a-form-item>
            <template v-if='formData.type === "FOLD" || formData.type === "PAGE"'>
                <a-form-item :label='$t("sort")' name='sort'>
                    <a-input type='number' v-model:value.number='formData.sort' />
                </a-form-item>
                <a-form-item :label='$t("display")' name='display'>
                    <a-switch v-model:checked='formData.display' :checked-children='$t("yes")' :un-checked-children='$t("no")'/>
                </a-form-item>
            </template>
            <a-form-item :label='$t("enable")' name='enable'>
                <a-switch v-model:checked='formData.enable' :checked-children='$t("enable")' :un-checked-children='$t("disable")'/>
            </a-form-item>
            <a-form-item v-if='formData.type === "PAGE"' label='keep Alive' name='keepAlive'>
                <a-switch v-model:checked='formData.keepAlive' :checked-children='$t("yes")' :un-checked-children='$t("no")'/>
            </a-form-item>
        </a-form>
    </BDialog>
</template>

<script lang='ts' setup>
    import { computed, nextTick, ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { deleteApi, listApi, saveApi, menuTypeApi, apiMethodTypeApi } from "@/api/system/Menu";
    import { recursionFn } from "@/utils";
    import { useI18nStore } from "@/store/i18n";
    
    const i18n = useI18nStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()

    const columns = ref<Column[]>([
        {
            dataIndex : 'name',
            title : i18n.t('name'),
            translate : true,
        },

        {
            dataIndex : 'type',
            title : i18n.t('type'),
        },

        {
            dataIndex : 'sort',
            title : i18n.t('sort'),
        },

        {
            dataIndex : 'enable',
            title : i18n.t('enable'),
        },

        {
            dataIndex : 'display',
            title : i18n.t('display'),
        },

        {
            dataIndex : 'keeAlive',
            title : 'Keep Alive'
        },

        {
            dataIndex : 'path',
            title : i18n.t('path'),
        },

        {
            dataIndex : 'component',
            title : i18n.t('component'),
        },

        {
            dataIndex : 'permission',
            title : i18n.t('permissionSymbol')
        },

        {
            dataIndex : 'api',
            title : 'Api'
        },

        {
            dataIndex : '$action',
            title : i18n.t('operation'),
            align : 'center',
            $edit(row) {
                dialogTitle.value = i18n.t('edit')
                for(let k in formData.value) {
                    formData.value[k] = row[k]
                }
                
                nextTick(() => {
                    visible.value = true
                })
            },

            async $delete(row, index) {
                const res = await deleteApi(row.id)
                if(res.success) {
                    getList()
                    message.success(i18n.t('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            }
            
        },
    ])

    const dataRows = ref<any[]>([])
    const typesOptions = ref<any[]>([])
    const apiMethodOptions = ref<any[]>([])

    const parentOptions = computed(() => [{id : 0, label : i18n.t('rootMenu'), children : dataRows.value}])

    const model = {
        id : 0,
        parentId : 0,
        type : '',
        name : '',
        path : '',
        component : '',
        permission : '',
        api : '',
        apiMethod : '',
        sort : 1,
        display : true,
        enable : true,
        keepAlive : false,
        visible : true,
    }


    const formData = ref<any>({})
        for(let k in model) {
            formData.value[k]  = model[k]
        }


    const rules = {
        parentId : [
            {
                required : true,
            }
        ],

        type : [
            {
                required : true,
                message : i18n.concat('please', 'select', 'type'),
            }
        ],

        name : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'name'),
            }
        ],

        path : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'path'),
            }
        ],

        component : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'component'),
            }
        ]
    }
    
    function getList() {
        listApi().then(res => {
            if(res.data.length > 0) {
                res.data.forEach(row => {
                    row.label = i18n.t(row.name)
                })
                dataRows.value = recursionFn(res.data, Math.min(...res.data.map(row => row.parentId)), 'id', 'parentId', 'children')
        
            }
        })
    }

    function close() {
        formRef.value.resetFields()
        formRef.value.clearValidate()

        
    }

    function addNew(parent) {
        for(let k in model) {
            formData.value[k]  = model[k]
        }
        
        formData.value.parentId = parent ? parent.id : 0
        dialogTitle.value = i18n.t('add')
        visible.value = true
        
    }

    async function submit() {
        let params  = await formRef.value.validate()
        if('sort' in params && params.sort === '') {
            params.sort = 0
        }
        
        const res = await saveApi(params)
        if(res.success) {
            getList()
            message.success(i18n.t('saveSuccess'))
            close()
            visible.value = false
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    getList()

    menuTypeApi().then(types => {
        typesOptions.value.push(...types.map(type => ({label : i18n.t(type.name), value : type.code})))
    })

    apiMethodTypeApi().then(types => {
        apiMethodOptions.value.push(...types.map(type => ({label : i18n.t(type.name), value : type.code})))
    })

</script>